<?php
class CP_SettingsController extends XPHP_Controller
{	
	public function _init()
	{
		$this->loadLayout("Administrator");
	}
	public function indexAction($args)
	{
		
		$model = new Areas_CP_Models_Settings($args[0]);

		return $this->view($model);
	}
	
	/**
	 * [[
	 * model: Areas_CP_Models_Settings
	 * ]]
	 */
	public function indexPOST()
	{
		if ($this->hasModel())
		{
			if ($this->model->isValid())
			{
				$this->model->update();
				return $this->redirect("index",array(1));
			}
		}
	}
	
	public function topMenuAction()
	{
		$modelTopMenu = new Areas_CP_Models_Topmenu();
		$arrTopMenu = $modelTopMenu->select_all();
		$modelNC = new Areas_CP_Models_NewsCategories();
		//Lấy danh sách vị trí
		$html = '';
		$i = 1;
		foreach ($arrTopMenu as $item)
		{
			$html .= '<option value="' . $i . '">' . $i . '</option>';
			$i++;
		}
		$condition = "";
		foreach ($arrTopMenu as $item)
		{
			if ($condition == "")
				$condition .= "id != ".$item['categoryID'];
			else
				$condition .= " and id != ".$item['categoryID'];
		}
		$arrNC = $modelNC->select_all($condition, "name ASC");
		//Sắp xếp danh mục cha con
		$arrData = array();
		foreach ($arrNC as $key => $item)
		{
			if ($item['parentID'] == 0)
			{
				$arrData[$key] = $item;
				foreach ($arrNC as $key2 => $item2) {
					if ($item2['parentID'] == $item['id'])
						$arrData[$key2] = $item2;
				}
			}
		}
		$this->view->option = $html;
		$this->view->arrNC = $arrData;
		$this->view->modelNC = $modelNC;
		$this->view->arrTopMenu = $arrTopMenu;
		return $this->view();
	}
	
	public function createAction()
	{
		
	}
	
	
	/**
	 * [[
	 * model: Areas_CP_Models_TopMenu
	 * ]]
	 */
	public function createAJAX()
	{
		$this->model->categoryID = $this->params['categoryID'];
		$this->model->position = 0;
		$this->model->insert();
		//Trả về RedirectResult tới action index
		return $this->json(array("success" => true));
	}
	
	public function deleteAJAX($args)
	{
		$id = $this->params['id'];
		$model = new Areas_CP_Models_Topmenu($id);
		$model->delete();
		return $this->json(array("success" => true));
	}
	
	public function changePosAction()
	{}
	
	public function changePosAJAX()
	{
		$model = new Areas_CP_Models_Topmenu();
		
		$model->update(array("position" => $this->params['old']), 'position='.$this->params['pos']);
		$model->update(array("position" => $this->params['pos']), 'id='.$this->params['id']);
		return $this->json(array("success" => true));
	}
}